package com.szboanda.parser.impl;

import com.szboanda.parser.ISqlParser;
import com.szboanda.parser.SqlParserException;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：zhangsheng
 * @date ：Created in 2020/2/24 10:24
 * @description：值替换参数解析,例如： ##{parame}
 * @modified By：
 * @version: 1.0$
 */
public class ValueReplaceParamParserImpl implements ISqlParser {


    /**
     * 脚本参数匹配：##{parame}
     */
    private static final Pattern SCRIPT_PARAM_PATTERN = Pattern.compile("##\\{\\s*?(?<startValue>.*?)\\s*?\\}");


    @Override
    public String parse(String sqlScript, List<Object> sqlArgs, Map<String, ?> context) {
        Map<String, String> vars = new HashMap<String, String>();
        Matcher match = SCRIPT_PARAM_PATTERN.matcher(sqlScript);
        while (match.find()) {
            String key = match.group(0);
            if(key.startsWith("##")){
                //值替换，不需要加入vars集合中
                String value = match.group("startValue").trim();
                if (null == context.get(value)) {
                    throw new SqlParserException(String.format("数据集%s自动注入异常，缺少参数%s", sqlScript, value));
                } else {
                    Object realValue = context.get(value);
                    if (realValue instanceof List) {
                        List<?> vals = (List)realValue;
                        String manyArgs = "(" +  StringUtils.join(vals, ',') + ")";
                        sqlScript = sqlScript.replace(key, manyArgs);
                    } else if (realValue.getClass().isArray()) {
                        Object[] vals = (Object[])realValue;
                        sqlArgs.addAll(Arrays.asList(vals));
                        String manyArgs = "(" +  StringUtils.join(vals, ',') + ")";
                        sqlScript = sqlScript.replace(key, manyArgs);
                    } else {
                        sqlScript = sqlScript.replace(key, realValue.toString());
                    }
                }
            }
        }
        //占位符sql语句
        for (String replace :  vars.keySet()) {
            sqlScript = sqlScript.replace(replace, "?");
        }
        return sqlScript;
    }
}
